import os
from flask import request, send_file, jsonify
import mistune


from basic.config import GlobalInfo, GlobalCfg
from modules.module import WebsiteModule


class KnowledgeLib(WebsiteModule):
    def __init__(self, parent):
        super(KnowledgeLib, self).__init__(parent, 'knowledgelib', '一个基于文件夹、markdown的文件网站，可以用来记录一些乱七八糟的东西。')
        self.library = GlobalCfg.knowledgelib_cfg
        
        self.add_routes('knowledgelib_view_file', '/knowledgelib_view_file', self.view_file, ['POST'])
        self.add_routes('knowledgelib_view_file_list', '/knowledgelib_view_file_list', self.view_file_list)
    
    
    def enable(self):
        if GlobalCfg.knowledgelib_cfg is None or GlobalCfg.knowledgelib_cfg == "":
            return False
            
        return True
        
    def homepage(self):
        return self.send_file('knowledgelib.html')
        
    # 获取指定文件夹中的所有文件和子目录
    def view_file_list(self):
        def _detect_path(_path):
            toc = []
            for item in os.listdir(_path):
                item_path = os.path.join(_path, item)
                if os.path.isfile(item_path):
                    toc.append(item)
                elif os.path.isdir(item_path):
                    subdir_content = _detect_path(item_path)
                    toc.append({item: subdir_content})
            return toc
        
        return jsonify(_detect_path(self.library))


    # 显示文件
    def view_file(self):
        file_path = request.form['file_path']
        file_path = os.path.join(GlobalCfg.knowledgelib_cfg, file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()

